package com.zhilianbao.leyaogo.ui.adapter.shoppingcart;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bql.animationcheckbox.AnimationCheckBox;
import com.bql.recyclerview.swipe.SwipeMenuAdapter;
import com.bql.roundview.RoundTextView;
import com.bql.utils.CheckUtils;
import com.zhilianbao.leyaogo.R;
import com.zhilianbao.leyaogo.model.response.shoppingcart.GoodsSKU;
import com.zhilianbao.leyaogo.model.response.shoppingcart.ShoppingCartGood;
import com.zhilianbao.leyaogo.ui.fragment.shoppingcart.ShoppingCartFragment;
import com.zhilianbao.leyaogo.utils.ImageUtils;
import com.zhilianbao.leyaogo.utils.Utils;
import com.zhilianbao.leyaogo.view.widgets.AddOrMinusView;
import com.zhilianbao.leyaogo.view.widgets.MoneyTextView;

import java.util.List;

/**
 * Author: hcy
 * Description:购物车设配器
 * Created: 2016/10/23 15:55
 */
public class ShoppingCartAdapter extends SwipeMenuAdapter<RecyclerView.ViewHolder> {

    private Context mContext;
    private List<ShoppingCartGood> mListData;

    public ShoppingCartAdapter(Context context, List<ShoppingCartGood> listData) {
        mContext = context;
        mListData = listData;
    }

    private boolean isNumClickable = true;

    /**
     * Fragment点击全选按钮，调用
     */
    public void setAllSelectChange() {
        notifyDataSetChanged();
    }

    public void setNumClickable(boolean clickable) {
        isNumClickable = clickable;
    }

    @Override
    public View onCreateContentView(ViewGroup parent, int viewType) {
        if (viewType == ShoppingCartFragment.TYPE_ACTIVITY_TITLE) {
            return LayoutInflater.from(mContext).inflate(R.layout.item_shopping_cart_title, parent, false);
        } else if (viewType == ShoppingCartFragment.TYPE_GOOD_ACTIVITY || viewType == ShoppingCartFragment.TYPE_GOOD_UNUSEABLE) {
            View view = new View(mContext);
            ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, mContext.getResources().getDimensionPixelSize(R.dimen.pay_order_deliver));
            view.setLayoutParams(lp);
            view.setBackgroundColor(mContext.getResources().getColor(R.color.common_bg_color_4));
            return view;
        } else {
            return LayoutInflater.from(mContext).inflate(R.layout.item_shopping_cart_goods, parent, false);
        }
    }

    @Override
    public RecyclerView.ViewHolder onCompatCreateViewHolder(View realContentView, int viewType) {
        if (viewType == ShoppingCartFragment.TYPE_ACTIVITY_TITLE) {
            return new TitleViewHolder(realContentView);
        } else if (viewType == ShoppingCartFragment.TYPE_GOOD) {
            return new CartViewHolder(realContentView);
        } else {
            return new SpaceViewHolder(realContentView);
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        ShoppingCartGood cartGood = mListData.get(position);
        if (cartGood.getType() == ShoppingCartFragment.TYPE_GOOD) {//数据
            setNormalData(holder, cartGood, position);
        } else if (cartGood.getType() == ShoppingCartFragment.TYPE_ACTIVITY_TITLE) {//活动标题
            setTitleData(holder, cartGood, position);
        } else {//2，3是分割条，不用设置数据
            if (position == 0) {//第一个不显示分割条
                holder.itemView.setVisibility(View.GONE);
            } else {
                holder.itemView.setVisibility(View.VISIBLE);
            }
        }
    }

    /**
     * 活动标题
     */
    private void setTitleData(RecyclerView.ViewHolder holder, ShoppingCartGood cartGood, int position) {
        TitleViewHolder titleHolder = (TitleViewHolder) holder;
        if (position == 0) {
            titleHolder.deliver.setVisibility(View.GONE);
        } else {
            titleHolder.deliver.setVisibility(View.VISIBLE);
        }
        titleHolder.desTv.setText(cartGood.getTitleDes());
        //1 特价 2 新人专享 3 包邮 4满减 ,
        switch (cartGood.getActivityType()) {
            case ShoppingCartFragment.SALE:
                titleHolder.rtv.setText(cartGood.getTitle());
                titleHolder.buyTv.setText("");
                break;
            case ShoppingCartFragment.NEW:
                titleHolder.buyTv.setText("");
                titleHolder.rtv.setText(cartGood.getTitle());
                break;
            case ShoppingCartFragment.FREE:
                titleHolder.buyTv.setText(cartGood.isMatch() ? mContext.getString(R.string.match) : mContext.getString(R.string.go_add_order));
                titleHolder.rtv.setText(cartGood.getTitle());
                break;
            case ShoppingCartFragment.SUBTRACT:
                titleHolder.buyTv.setText(cartGood.isMatch() ? mContext.getString(R.string.match) : mContext.getString(R.string.go_add_order));
                titleHolder.rtv.setText(cartGood.getTitle());
                break;
        }
        titleHolder.rootView.setTag(position);

    }

    /**
     * 正常商品
     */
    private void setNormalData(RecyclerView.ViewHolder holder, ShoppingCartGood cartGood, int position) {
        CartViewHolder cartViewHolder = (CartViewHolder) holder;
        setState(cartGood.getState(), cartViewHolder);
        if (cartGood.getState() == ShoppingCartFragment.STATE_USEABLE) {
            isNormalGoodStockOk(cartViewHolder, cartGood);
        } else {
            cartViewHolder.notEnoughTv.setVisibility(View.GONE);
        }
        cartViewHolder.titleTv.setText(cartGood.getGoodsName());
        String subText = "";
        if (cartGood.getGoodsType() == 1) {//sku 商品 subTv显示规格
            GoodsSKU goodsSKU = Utils.getSkuGood(cartGood);
            if (!CheckUtils.isNull(goodsSKU)) {
                subText = goodsSKU.getItemVals();
            }
        } else {
            subText = cartGood.getGoodsDesc();
        }
        cartViewHolder.subTv.setText(subText);
        cartViewHolder.saleTv.setAmount(cartGood.getActivityType() == 1 || cartGood.getActivityType() == 2 ? cartGood.getDiscountPrice() : Utils.getGoodPrice(cartGood));
        ImageUtils.loadGoodsPic(Utils.returnUrlShow(cartGood.getGoodsPic()), cartViewHolder.iv);

        //可购买商品，设置checkbox 选择监听
        if (cartGood.getState() == ShoppingCartFragment.STATE_USEABLE) {
            //是否选中
            if (cartGood.isChecked()) {
                cartViewHolder.checkBox.setChecked(true, false, false);
            } else {
                cartViewHolder.checkBox.setChecked(false, false, false);
            }

            cartViewHolder.checkBox.setTag(position);
            cartViewHolder.checkBox.setOnCheckedChangeListener(new AnimationCheckBox.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(AnimationCheckBox checkBox, boolean isChecked) {
                    ShoppingCartGood goods = mListData.get((Integer) checkBox.getTag());
                    goods.setChecked(isChecked);
                    if (mCheckChangeListener != null) {
                        mCheckChangeListener.checkChange(isChecked, position);
                    }
                }
            });
            cartViewHolder.acbView.setTag(position);
            cartViewHolder.acbView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ShoppingCartGood goods = mListData.get((Integer) v.getTag());
                    cartViewHolder.checkBox.setChecked(!goods.isChecked(), true);
                }
            });
        }

        //type1,2,4的活动限购数量(新人专享，特价，满减)
        if (cartGood.getLimitCount() != 0 && cartGood.getNumber() <= cartGood.getLimitCount()) {//满足活动
            cartViewHolder.limitCountTv.setVisibility(View.VISIBLE);
            cartViewHolder.limitCountTv.setText(String.format(mContext.getString(R.string.limit_count), cartGood.getLimitCount()));
        } else {
            cartViewHolder.limitCountTv.setText("");
            cartViewHolder.limitCountTv.setVisibility(View.GONE);
        }

        //隐藏分割线
        if (position == mListData.size() - 1) {
            cartViewHolder.line.setVisibility(View.INVISIBLE);
        } else {
            cartViewHolder.line.setVisibility(View.VISIBLE);
        }
        int tempPos = position + 1;
        if (tempPos < mListData.size()) {
            if (mListData.get(tempPos).getType() == ShoppingCartFragment.TYPE_GOOD_ACTIVITY
                    || mListData.get(tempPos).getType() == ShoppingCartFragment.TYPE_GOOD_UNUSEABLE
                    || mListData.get(tempPos).getType() == ShoppingCartFragment.TYPE_ACTIVITY_TITLE) {
                cartViewHolder.line.setVisibility(View.INVISIBLE);
            } else {
                cartViewHolder.line.setVisibility(View.VISIBLE);
            }
        }

        //不是可用商品，不用设置增加减少按钮点击监听
        if (cartGood.getState() != ShoppingCartFragment.STATE_USEABLE) {
            return;
        }
        cartViewHolder.addOrMinusView.setTagData(position);
        cartViewHolder.addOrMinusView.setShowerCount(cartGood.getNumber());
        //商品能否减
        //        if (cartGood.getNumber() == 1) {
        //            cartViewHolder.addOrMinusView.setMinIvResource(R.drawable.icon_substract_gray);
        //            cartViewHolder.addOrMinusView.setSubRespond(false);
        //        } else {
        //            cartViewHolder.addOrMinusView.setMinIvResource(R.drawable.icon_subtract);
        //            cartViewHolder.addOrMinusView.setSubRespond(true);
        //        }

        cartViewHolder.addOrMinusView.setOnPrepareCountAddOrMinusListener(new AddOrMinusView.OnPrepareCountAddOrMinusListener() {
            @Override
            public boolean prepareAdd(Object data, int currentCount, int nextCount, boolean respond) {
                if (mNumChangeListener != null && isNumClickable) {
                    isNumClickable = false;
                    mNumChangeListener.add(nextCount, (Integer) data);
                }
                return true;
            }

            @Override
            public boolean prepareMinus(Object data, int currentCount, int nextCount, boolean respond) {
                if (mNumChangeListener != null && isNumClickable) {
                    isNumClickable = false;
                    mNumChangeListener.subtract(nextCount, currentCount, (Integer) data);
                }
                return true;
            }
        });

    }

    /**
     * 设置显示状态
     *
     * @param state
     * @param cartViewHolder
     */
    private void setState(int state, CartViewHolder cartViewHolder) {
        switch (state) {
            case ShoppingCartFragment.STATE_USEABLE://正常
                cartViewHolder.outOfTimeTv.setVisibility(View.INVISIBLE);
                cartViewHolder.checkBox.setVisibility(View.VISIBLE);
                cartViewHolder.outOfTimeDesTv.setVisibility(View.GONE);
                cartViewHolder.saleTv.setVisibility(View.VISIBLE);
                cartViewHolder.addOrMinusView.setVisibility(View.VISIBLE);
                cartViewHolder.subTv.setVisibility(View.VISIBLE);
                cartViewHolder.itemView.setBackgroundColor(mContext.getResources().getColor(R.color.white));
                cartViewHolder.titleTv.setTextColor(mContext.getResources().getColor(R.color.color_333333));
                break;
            case ShoppingCartFragment.STATE_OUT_STOCK://商品下架，
                cartViewHolder.outOfTimeDesTv.setText(mContext.getString(R.string.out_stock));
                setUnUseState(cartViewHolder);
                break;
            case ShoppingCartFragment.STATE_NOT_ENOUGH://库存为0
                cartViewHolder.outOfTimeDesTv.setText(mContext.getString(R.string.not_more));
                setUnUseState(cartViewHolder);
                break;
            case ShoppingCartFragment.STATE_DEL://商品已删除
                cartViewHolder.outOfTimeDesTv.setText(mContext.getString(R.string.del_flag));
                setUnUseState(cartViewHolder);
                break;
        }
    }

    /**
     * 失效商品状态
     *
     * @param cartViewHolder holder
     */
    private void setUnUseState(CartViewHolder cartViewHolder) {
        cartViewHolder.outOfTimeTv.setVisibility(View.VISIBLE);
        cartViewHolder.checkBox.setVisibility(View.INVISIBLE);
        cartViewHolder.outOfTimeDesTv.setVisibility(View.VISIBLE);
        cartViewHolder.saleTv.setVisibility(View.GONE);
        cartViewHolder.addOrMinusView.setVisibility(View.GONE);
        cartViewHolder.subTv.setVisibility(View.GONE);
        cartViewHolder.itemView.setBackgroundColor(mContext.getResources().getColor(R.color.color_f2f2f2));
        cartViewHolder.titleTv.setTextColor(mContext.getResources().getColor(R.color.color_cccccc));
    }

    /**
     * 可用商品库存是否大于购买数量
     */
    private void isNormalGoodStockOk(CartViewHolder cartViewHolder, ShoppingCartGood good) {
        if (good.getNumber() > Utils.getStockNumber(good)) {//购买数量大于库存数量
            cartViewHolder.notEnoughTv.setVisibility(View.VISIBLE);
        } else {
            cartViewHolder.notEnoughTv.setVisibility(View.GONE);
        }
    }

    @Override
    public int getItemCount() {
        return mListData == null ? 0 : mListData.size();
    }

    @Override
    public int getItemViewType(int position) {
        return mListData.get(position).getType();
    }

    /**
     * 外部监听接口
     */
    public interface CheckChangeListener {
        void checkChange(boolean isChecked, int position);
    }

    public interface OnNumChangeListener {
        void add(int num, int pos);

        void subtract(int num, int currCount, int pos);
    }

    private CheckChangeListener mCheckChangeListener;
    private OnNumChangeListener mNumChangeListener;

    public void setCheckChangeListener(CheckChangeListener listener) {
        mCheckChangeListener = listener;
    }

    public void setOnNumChangeListener(OnNumChangeListener listener) {
        mNumChangeListener = listener;
    }

    private static class CartViewHolder extends RecyclerView.ViewHolder {
        //ContentView element
        public TextView titleTv, subTv;
        public MoneyTextView saleTv;
        public ImageView iv;
        public AnimationCheckBox checkBox;
        public AddOrMinusView addOrMinusView;
        public View acbView;
        public TextView notEnoughTv;
        public TextView outOfTimeTv;
        public TextView outOfTimeDesTv;
        public TextView limitCountTv;//活动type1,2特价，新人专享的限制购买数量
        public LinearLayout itemView;
        public View line;

        public CartViewHolder(View itemView) {
            super(itemView);
            titleTv = (TextView) itemView.findViewById(R.id.tv_title);
            subTv = (TextView) itemView.findViewById(R.id.tv_sub_title);
            saleTv = (MoneyTextView) itemView.findViewById(R.id.tv_price);
            iv = (ImageView) itemView.findViewById(R.id.iv_goods_img);
            checkBox = (AnimationCheckBox) itemView.findViewById(R.id.anim_check_box);
            addOrMinusView = (AddOrMinusView) itemView.findViewById(R.id.add_or_minus_view);
            acbView = itemView.findViewById(R.id.fl_acb);
            notEnoughTv = (TextView) itemView.findViewById(R.id.tv_not_enough);
            outOfTimeTv = (TextView) itemView.findViewById(R.id.tv_out);
            outOfTimeDesTv = (TextView) itemView.findViewById(R.id.tv_out_des);
            limitCountTv = (TextView) itemView.findViewById(R.id.tv_limit_count);
            line = itemView.findViewById(R.id.line);
            this.itemView = (LinearLayout) itemView.findViewById(R.id.root_view);
        }

    }

    private static class TitleViewHolder extends RecyclerView.ViewHolder {
        //title
        public TextView desTv, buyTv;
        public View deliver;
        public RoundTextView rtv;
        public View rootView;

        public TitleViewHolder(View itemView) {
            super(itemView);
            desTv = (TextView) itemView.findViewById(R.id.tv_des);
            deliver = itemView.findViewById(R.id.deliver);
            buyTv = (TextView) itemView.findViewById(R.id.tv_buy);
            rtv = (RoundTextView) itemView.findViewById(R.id.iv_tag);
            rootView = itemView;
        }

    }

    private static class SpaceViewHolder extends RecyclerView.ViewHolder {
        public SpaceViewHolder(View itemView) {
            super(itemView);
        }
    }

}
